package com.izhar.answeringmachine.service.Impl;

import com.izhar.answeringmachine.Entity.RunFail;
import com.izhar.answeringmachine.Entity.SubmitCode;
import com.izhar.answeringmachine.mapper.RunFailMapper;
import com.izhar.answeringmachine.mapper.SubmitCodeMapper;
import com.izhar.answeringmachine.service.ISaveFail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
@Deprecated
public class SaveFailImpl implements ISaveFail {

    @Autowired
    protected RunFailMapper runFailMapper;

    @Autowired
    protected SubmitCodeMapper submitCodeMapper;

    private RunFail runFail = new RunFail();

    private SubmitCode submitCode = new SubmitCode();

    @Override
    public String save(String reason,String submitCodeId, Map<String, String> map) {
        //UUID生成id
        String id = "";
        synchronized (this.getClass()){
            id = UUID.randomUUID().toString();
        }

        String sampleId = "";
        String errResult = "";
        for (String s : map.keySet()) {
            sampleId = s;
            errResult = map.get(sampleId);
        }

        if (sampleId==null || sampleId.trim().equals("") || errResult==null || errResult.trim().equals("")) {
            throw new RuntimeException("SaveService: sampleId or errResult is null");
        }

        runFail.setId(id);
        runFail.setReason(reason);
        runFail.setSampleId(sampleId);
        runFail.setErrorResult(errResult);
        runFail.setCreateTime(new Date());

        submitCode.setReason(id);
        submitCode.setUpdateTime(new Date());
        submitCode.setId(submitCodeId);
        submitCode.setPass(2);
        DbOperator();
        return id;
    }

    @Override
    public void setPass(String submitCodeId, Integer pass) {
        submitCodeMapper.setPass(submitCodeId,pass);
    }

    @Transactional(rollbackFor = Exception.class)
    public void DbOperator(){
        //配置的错误类 放到数据库
        runFailMapper.insert(runFail);
        //错误类的id 填到提交库的reason中
        submitCodeMapper.updateErrReason(this.submitCode);
    }
}
